package com.dcjt.firehotcarpad.service

import LocationPool
import NewMessagePool
import android.annotation.SuppressLint
import android.app.Service
import android.content.Intent
import android.os.IBinder
import com.aries.library.fast.manager.LoggerManager
import com.aries.library.fast.retrofit.FastObserver
import com.aries.library.fast.util.FastStackUtil
import com.aries.library.fast.util.FastUtil
import com.aries.library.fast.util.SPUtil
import com.aries.library.fast.util.ToastUtil
import com.dcjt.firehotcarpad.base.App
import com.dcjt.firehotcarpad.base.App.Companion.get
import com.dcjt.firehotcarpad.base.SPConstant
import com.dcjt.firehotcarpad.entity.*
import com.dcjt.firehotcarpad.manager.DataManager
import com.dcjt.firehotcarpad.manager.TtsManager
import com.dcjt.firehotcarpad.moudle.HandleDisasterActivity
import com.dcjt.firehotcarpad.moudle.LoginActivity
import com.dcjt.firehotcarpad.retrofit1.repository.ApiRepository1
import com.dcjt.firehotcarpad.utils.MessageUtil
import com.dcjt.firehotcarpad.utils.MessageUtils
import com.dcjt.firehotcarpad.utils.ServiceUtils
import com.dcjt.firehotcarpad.utils.StringUtils
import com.google.gson.Gson
import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.ResponseBody
import org.json.JSONArray
import org.json.JSONObject
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetAddress
import java.util.concurrent.TimeUnit


class MessageService : Service() {
    private val userEntity = DataManager.getInstance().user
    var imei: String? = null
    var isLoginOut: Boolean = false
    var mSocket: DatagramSocket? = null

    @SuppressLint("CheckResult")
    override fun onCreate() {
        super.onCreate()
        imei = SPUtil.get(get(), SPConstant.IMEI, "") as String
        if (StringUtils.isEmpty(imei)) {
            imei = StringUtils.getIMEI()
            SPUtil.put(get(), SPConstant.IMEI, imei)
        }
        TtsManager.get().initTts(this)
        requestPMQ(DataManager.getInstance().user.id)
        uploadLocation()

    }


    private var confirm = ""
    private var mCompositeDisposable = CompositeDisposable()


    override fun onBind(intent: Intent): IBinder? {
        return null
    }

    /**
     * 定时获取消息（不建议）
     */
    private fun getMessage() {

        val disposable = Observable.timer(1000, TimeUnit.MILLISECONDS)
            .observeOn(Schedulers.io())
            .subscribe {
                requestPMQ(userEntity.id)
            }
        mCompositeDisposable.add(disposable)


    }

    /**
     * 请求接口
     * @param userId 消息接收对象id
     */
    private fun requestPMQ(userId: String) {
//        map["aid"] = Dat ] = Tools.getIMEI()
        if (DataManager.getInstance().pmqBean == null) {
            return
        }
        // 接收消息
        ApiRepository1.getInstance().takeMessageGET(
            DataManager.getInstance().pmqBean?.aid.toString(),
            DataManager.getInstance().pmqBean?.access_token.toString(),
            DataManager.getInstance().pmqBean.uid,
            "10",
            confirm,
            imei,
            SPUtil.get(App.get(), SPConstant.MESSAGE_URL_PORT, "") as String?
        ).subscribe(object : FastObserver<ResponseBody>() {


            override fun _onError(
                errorRes: Int,
                errorCode: Int,
                e: Throwable
            ) {
                super._onError(errorRes, errorCode, e)
                requestPMQ(userId)
                LoggerManager.d("takeerror" + errorRes)
            }

            override fun _onNext(entity: ResponseBody) {
                val response: String = entity.string()
                try {
                    val msg =
                        MessageUtils.uncompress(
                            response.substring("PMQ/gz".length)
                        )
                    LoggerManager.d("takesuccess" + msg)
                    parseMessage(true, msg)
                } catch (e: Exception) {
                    e.printStackTrace()
                } finally {
                    if (!isLoginOut){
                        requestPMQ(userId)
                    }
                }
            }
        })

    }

    /**
     * 解析消息
     * @param isMsg 是否是消息
     * @param info 消息内容
     */
    @SuppressLint("CheckResult")
    private fun parseMessage(isMsg: Boolean, info: String) {
        val obj = JSONObject(info)
        val code = obj.optInt("code")

        // 返回数据正常
        if (code == 0) {
            if (isMsg) {
                val data = obj.optJSONObject("data")
                // 空消息返回数组，有消息返回对象
                data ?: return
                LoggerManager.d("parseMessage--$info")
                // 已经接收的消息id
                confirm = data.optString("confirm")
                val array = data.optJSONArray("array") ?: JSONArray("[]")
                for (i in 0 until array.length()) {
                    val msg = array.getJSONObject(i)
                    if (msg.optString("data") == "rebacker") return
                    val item = JSONObject(
                        MessageUtils.unCompile(
                            msg.optString("data")
                        )
                    )
                    LoggerManager.e("takes解析item:" + item)

                    val msgData = item.optJSONObject("msg")
                    msgData ?: return
                    LoggerManager.e("takes解析msg:" + msgData)
                    when (item.optString("cmd")) {
                        //标绘修改
                        SPConstant.BUZ_ZZBH_SET -> {
                            val zqId = msgData.optString("zqid") ?: ""
                            NewMessagePool.get().sendUploadBiaohuiDispatch(zqId)
                        }
                        //指令消息
                        DataManager.getInstance().appConfigEntity.jcj_pmqEnum.jcJ_Cmd.zhzX_RWZL -> {

                            var zlMessage =
                                Gson().fromJson(Gson().toJson(msgData), MessageZlEntity::class.java)
                            run outside@{
                                if (zlMessage.nameValuePairs!!.data!!.nameValuePairs!!.jsdw == null || zlMessage.nameValuePairs!!.data!!.nameValuePairs!!.jsdw!!.values!!.size == 0) {
                                    return@outside
                                } else {
                                    zlMessage.nameValuePairs!!.data!!.nameValuePairs!!.jsdw!!.values!!.forEach {
                                        if (it.nameValuePairs!!.jsdwid == DataManager.getInstance().user.id) {
                                            //发送消息
                                            NewMessagePool.get().sendDispatch(
                                                EventEntity.MessageDetailEvent(
                                                    "",
                                                    0.0,
                                                    0.0,
                                                    0.0,
                                                    0.0,
                                                    DataManager.getInstance().appConfigEntity.jcj_pmqEnum.jcJ_Cmd.zhzX_RWZL,
                                                    zlMessage.nameValuePairs!!.data!!.nameValuePairs
                                                )
                                            )
                                            return@outside
                                        }
                                    }

                                }
                            }
                        }
                        //新的警情消息
                        DataManager.getInstance().appConfigEntity.jcj_pmqEnum.jcJ_Cmd.buZ_ZQXX_SAVE -> {

                            //新的警情消息    判断车辆id
                            var newDisasterMessage =
                                Gson().fromJson(
                                    Gson().toJson(msgData),
                                    NewDisasterMessage::class.java
                                )
                            run outside@{
                                newDisasterMessage.nameValuePairs!!.ddclxx!!.values!!.forEach {

                                    if (it.nameValuePairs!!.id.equals(DataManager.getInstance().user.account)) {
                                        //发送消息  分发消息
                                        NewMessagePool.get().sendDispatch(
                                            EventEntity.MessageDetailEvent(
                                                newDisasterMessage.nameValuePairs!!.zqid!!,
                                                0.0,
                                                0.0,
                                                0.0,
                                                0.0,
                                                DataManager.getInstance().appConfigEntity.jcj_pmqEnum.jcJ_Cmd.buZ_ZQXX_SAVE,
                                                null
                                            )
                                        )
                                        return@outside
                                    }
                                }
                            }
                        }
                        //修改车辆状态
                        DataManager.getInstance().appConfigEntity.jcj_pmqEnum.jcJ_Cmd.buZ_CLZT_SET_FCJQ,
                        DataManager.getInstance().appConfigEntity.jcj_pmqEnum.jcJ_Cmd.buZ_CLZT_SET_YJFD,
                        DataManager.getInstance().appConfigEntity.jcj_pmqEnum.jcJ_Cmd.buZ_CLZT_SET -> {

                            var clztSet =
                                Gson().fromJson(Gson().toJson(msgData), ClztSetEntity::class.java)
                            run outside@{
                                if (StringUtils.isEmpty(clztSet.nameValuePairs!!.clid)) {
                                    return@outside
                                } else {
                                    var clidArray = clztSet.nameValuePairs!!.clid.split(",")
                                    if (clidArray.isNotEmpty()) {
                                        clidArray.forEach {
                                            if (it.equals(DataManager.getInstance().user.account)) {
                                                //发送消息  分发消息
                                                NewMessagePool.get().sendDispatch(
                                                    EventEntity.MessageDetailEvent(
                                                        clztSet.nameValuePairs!!.zqid,
                                                        0.0,
                                                        0.0,
                                                        0.0,
                                                        0.0,
                                                        DataManager.getInstance().appConfigEntity.jcj_pmqEnum.jcJ_Cmd.buZ_CLZT_SET,
                                                        null
                                                    )
                                                )
                                                return@outside
                                            }
                                        }
                                    }
                                    //判断机构id 受否有
                                    if (clztSet.nameValuePairs!!.depts != null && clztSet.nameValuePairs!!.depts.values.size > 0) {
                                        clztSet.nameValuePairs!!.depts.values.forEach {
                                            if (DataManager.getInstance().user.dept_id == it) {
                                                //发送消息  分发消息
                                                NewMessagePool.get().sendDispatch(
                                                    EventEntity.MessageDetailEvent(
                                                        clztSet.nameValuePairs!!.zqid!!,
                                                        0.0,
                                                        0.0,
                                                        0.0,
                                                        0.0,
                                                        DataManager.getInstance().appConfigEntity.jcj_pmqEnum.jcJ_Cmd.buZ_CLZT_SET,
                                                        null
                                                    )
                                                )
                                                return@outside
                                            }
                                        }
                                    }
                                    //判断下发的zqid 是否为关联警情id
                                    if(clztSet.nameValuePairs!!.zqid!! == CarStatePool.get().getZqidGl()
                                        || clztSet.nameValuePairs!!.zqid!! == CarStatePool.get().getCurrentZqidPage()
                                    ){
                                        NewMessagePool.get().sendDispatch(
                                            EventEntity.MessageDetailEvent(
                                                clztSet.nameValuePairs!!.zqid!!,
                                                0.0,
                                                0.0,
                                                0.0,
                                                0.0,
                                                DataManager.getInstance().appConfigEntity.jcj_pmqEnum.jcJ_Cmd.buZ_CLZT_SET,
                                                null
                                            )
                                        )
                                    }
                                }
                            }
                        }

                        //车辆调度信息
                        DataManager.getInstance().appConfigEntity.jcj_pmqEnum.jcJ_Cmd.buZ_CLZT_ZNZHDP -> {
                            LoggerManager.e("车辆调度信息")
                            //收到新的车辆调度信息
                            var carDiaoduEntity =
                                Gson().fromJson(Gson().toJson(msgData), CarDiaoDuEntity::class.java)
                            run outside@{
                                carDiaoduEntity.nameValuePairs.clids.values.forEachIndexed { index, it ->
                                    //车辆id 判断
                                    if (it.nameValuePairs.id.equals(DataManager.getInstance().user.account)) {
                                        var ms = "收到新的车辆调度信息"
                                        NewMessagePool.get().sendDispatch(
                                            EventEntity.MessageDetailEvent(
                                                carDiaoduEntity.nameValuePairs.zqinfo.nameValuePairs.id,
                                                carDiaoduEntity.nameValuePairs.zqinfo.nameValuePairs.point.nameValuePairs.x,
                                                carDiaoduEntity.nameValuePairs.zqinfo.nameValuePairs.point.nameValuePairs.y,
                                                0.0,
                                                0.0,
                                                DataManager.getInstance().appConfigEntity.jcj_pmqEnum.jcJ_Cmd.buZ_CLZT_ZNZHDP,
                                                null
                                            )
                                        )
                                        return@outside
                                    }
                                }
                            }

                        }
                       //作战标绘记录改变
                        DataManager.getInstance().appConfigEntity.znzh_pmqEnum.znzH_TB_Cmd.tB_ZZBH_BHJL -> {
                            LoggerManager.e("作战标绘记录改变")
                            val zqId = msgData.optString("jqid") ?: ""
                            val bhdt = msgData.optJSONObject("data").optString("bhdt") ?: ""
                            if (StringUtils.isEmpty(bhdt) || !bhdt.equals("sn")){
                                NewMessagePool.get().sendUploadBiaohuiDispatch(zqId)
                            }
                        }
                        //标绘作战位置
                        DataManager.getInstance().appConfigEntity.znzh_pmqEnum.znzH_TB_Cmd.tB_ZZBH_RWXD -> {
                            //标绘作战位置
                            var carChangeEntity =
                                Gson().fromJson(Gson().toJson(msgData), CarChangeEntity::class.java)
                            //判断是否是自己的车
                            var isCarChange = false
                            run outside@{
                                //车辆位置
                                carChangeEntity.nameValuePairs.data.values.forEachIndexed { index, it ->
                                    if ("100103"!=it.nameValuePairs.bhdxlxdm && it.nameValuePairs.id.equals(DataManager.getInstance().user.account)) {
                                            var ms = "收到新的作战位置"
                                            if (it.nameValuePairs.ms!= null&&!StringUtils.isEmpty(it.nameValuePairs.ms as String?)) {
                                                ms = it.nameValuePairs.ms.toString()
                                            }
                                            LoggerManager.e("收到新的作战位置")
                                            NewMessagePool.get().sendDispatch(
                                                EventEntity.MessageDetailEvent(
                                                    carChangeEntity.nameValuePairs.zqinfo.nameValuePairs.id.toString(),
                                                    carChangeEntity.nameValuePairs.zqinfo.nameValuePairs.point.values.get(
                                                        0
                                                    ).values.get(0),
                                                    carChangeEntity.nameValuePairs.zqinfo.nameValuePairs.point.values.get(
                                                        0
                                                    ).values.get(1),
                                                    it.nameValuePairs.point.values.get(0),
                                                    it.nameValuePairs.point.values.get(1),
                                                    DataManager.getInstance().appConfigEntity.znzh_pmqEnum.znzH_TB_Cmd.tB_ZZBH_RWXD,
                                                    null
                                                )
                                            )
                                            isCarChange = true
                                            return@outside
                                        }
                                }


                            }
//                            //if isCarChange = true 证明该位置改变有本车信息，现进行集结点筛选
                            run outside@{
                                carChangeEntity.nameValuePairs.data.values.forEachIndexed { index, it ->
                                    if ("100103"==it.nameValuePairs.bhdxlxdm ) {
                                        LoggerManager.e("收到新的集结点位置")
                                        NewMessagePool.get().onObserverMessageJjd(
                                            EventEntity.MessageDetailEvent(
                                                carChangeEntity.nameValuePairs.zqinfo.nameValuePairs.id.toString(),
                                                0.0,
                                                0.0,
                                                it.nameValuePairs.point.values.get(0),
                                                it.nameValuePairs.point.values.get(1),
                                                "",
                                                null
                                            )
                                        )
                                        return@outside
                                    }
                                }
                            }
                        }
                        DataManager.getInstance().appConfigEntity.znzh_pmqEnum.znzH_TB_Cmd.tB_ZZBH_BHZ -> {
                            ToastUtil.show(" 作战标绘列表改变")
                            LoggerManager.e("作战标绘列表改变")
                        }

                        DataManager.getInstance().appConfigEntity.jcj_pmqEnum.jcJ_Cmd.buZ_SXH_SAVE -> {
                            LoggerManager.e("新的时序化消息")
                            NewMessagePool.get().onReceiveDocumentMsg()
                        }

                    }
                }
            } else {
                // 两个账号同时登录
                val array = obj.getJSONArray("data")
                if (array.length() > 1) {
                    for (i in 0 until array.length()) {
                        val app = array.getJSONObject(i)
                        if (app.optString("name") == MessageUtils.appName) {
                            MessageUtils.pmqAid = app.optString("aid")
                            MessageUtils.pmqToken = app.optString("access_token")
                            break
                        }
                    }
                }
            }


        } else if (code == 65000) {
            LoggerManager.e("该账号已在其他设备登录")
            ToastUtil.show("该账号已在其他设备登录")
            // 消息会将两个设备同时剔除
            val stack = FastStackUtil.getInstance().stack
                FastUtil.startActivity(FastStackUtil.getInstance().current, LoginActivity::class.java)
                stack.forEach {
                    it.finish()
                }
            isLoginOut = true

        }
    }

    private fun uploadLocation() {

        if (DataManager.getInstance().appConfigEntity == null) {
            ToastUtil.show("获取配置信息有误，请重新登录")
            return
        }

        val toHttpUrlOrNull =
            DataManager.getInstance().appConfigEntity.appServerUrl.gpsUrl.toHttpUrlOrNull()
        Observable.interval(15, TimeUnit.SECONDS)
            .observeOn(Schedulers.io())
            .subscribe {
                if (LocationPool.get().getCurrentLocation() != null) {
                    try {
                        if (mSocket == null) {
                            mSocket = DatagramSocket()
                        }
                        if (mSocket?.isConnected == false) {
                            mSocket?.connect(
                                InetAddress.getByName(toHttpUrlOrNull?.host),
                                toHttpUrlOrNull?.port!!
                            ) //连接
                        }


                        val buff = MessageUtil.getMessage(
                            DataManager.getInstance().gpsbh,
                            LocationPool.get().getCurrentLocation()!!
                        )
//                        val buff = MessageUtil.getMessage("798456123", 9.0,0.0);
                        val sendPacket = DatagramPacket(
                            buff,
                            buff.size,
                            InetAddress.getByName(toHttpUrlOrNull?.host),
                            toHttpUrlOrNull?.port!!
                        )
                        mSocket?.send(sendPacket)
                        LoggerManager.e("MessageService", "上传位置")
                    } catch (e: Exception) {
                        LoggerManager.e(e.message)
                    }

                } else {
                    LoggerManager.e("发送定位失败")
                }
            }
    }

    /**
     * 检查是否为必要消息
     * 目的是去除不需要自己处理的冗余消息
     */
    private fun checkShould(dept: JSONArray?): Boolean {
        var isHasOneself = false
        dept ?: return isHasOneself
        for (j in 0 until dept.length()) {
            if (userEntity.dept_id == dept.get(j).toString()) {
                isHasOneself = true
                continue
            }
        }
        if (isHasOneself.not()) {
            return true
        }
        return false
    }


    /**
     * 回收
     */
    override fun onDestroy() {
        super.onDestroy()
        mCompositeDisposable.clear()

        if (mSocket != null) {
            mSocket = null
        }
        TtsManager.get().stopTTs()

    }

}